
package com.jf.cloud.service.sysmanager.remote.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jf.cloud.service.sysmanager.dao.*;
import com.jf.cloud.service.sysmanager.entity.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.ObjectUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.MatchConstant;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.UserMatchConstant;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 俱乐部控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/appMatch")
public class AppPubgMatchController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(AppPubgMatchController.class);

	/**
	 * 俱乐部服务
	 */
	@Resource
	private IPubgClubService pubgClubService;

	@Resource
	private TokenHandler tokenHandler;

	@Resource
	private IPubgBaseTypeService pubgBaseTypeService;

	@Resource
	private IPubgMatchService pubgMatchService;

	@Resource
	private IPubgMatchRewardService pubgMatchRewardService;

	@Resource
	private IPubgTeamService pubgTeamService;

	@Resource
	private IPubgUserService pubgUserService;
	
	@Resource
	private IPubgUserTeamService pubgUserTeamService;

	@Resource
	private IPubgUserMatchService pubgUserMatchService;

	/**
	 * 添加赛事
	 *
	 */
	@ResponseBody
	@RequestMapping("/addMatch")
	public Result<PubgMatch> addMatch(String token, HttpServletRequest request){
		Result<PubgMatch> result = new Result<PubgMatch>();
		result.setCode(-1);
		result.setMessage("添加赛事失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			Query queryUser = new Query();
			queryUser.put("ROW_ID",userId);
			PubgUser pubgUser = this.pubgUserService.find(queryUser);


			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", "," + userId + ",");
			PubgClub pubgClub = this.pubgClubService.find(query);

			PubgMatch pubgMatch = new PubgMatch();

			pubgMatch.setClubId(pubgClub.getRowId());
			pubgMatch.setClubName(pubgClub.getClubName());

			// 赛事名称
			String matchName = request.getParameter("matchName");
			if (StringUtil.isNull(matchName)) {
				result.setMessage("赛事名称为空！");
				return result;
			}
			pubgMatch.setMatchName(matchName);

			//状态
			pubgMatch.setMatchState(MatchConstant.MATCH_STATE_10.getId()+"");

			// 比赛模式
			Query queryMode = new Query();
			String  modeId = request.getParameter("modeId");
			if (StringUtil.isNull(modeId)) {
				result.setMessage("比赛模式为空！");
				return result;
			}
			queryMode.put("TYPE_FLAG","40");
			queryMode.put("PARENT_ID","2");
			queryMode.put("ROW_ID",modeId);
			PubgBaseType pubgBaseMode = this.pubgBaseTypeService.find(queryMode);

			pubgMatch.setMatchModeId(pubgBaseMode.getRowId());
			pubgMatch.setMatchMode(pubgBaseMode.getTypeName());

			// 比赛类型
			Query queryType = new Query();
			Long matchTypeId = getLongValue(request,"matchTypeId");
			if (matchTypeId == null) {
				result.setMessage("比赛类型为空！");
				return result;
			}

			queryType.put("TYPE_FLAG","50");
			queryType.put("PARENT_ID","1");
			queryType.put("ROW_ID",matchTypeId);
			PubgBaseType pubgBaseType = this.pubgBaseTypeService.find(queryType);

			pubgMatch.setMatchTypeId(matchTypeId);
			pubgMatch.setMatchType(pubgBaseType.getTypeName());


			// 报名费
			Double applyFee = getParamValueDouble(request,"applyFee");
			if (applyFee == null) {
				result.setMessage("报名费为空！");
				return result;
			}
			pubgMatch.setApplyFee(applyFee);

			//AWARD_WAY 针对用户的按利润
			pubgMatch.setAwardWay(0.0);

			// 房间名称密码
			String roomName = request.getParameter("roomName");
			if (StringUtil.isNull(roomName)) {
				result.setMessage("房间名称为空！");
				return result;
			}
			String roomPwd = request.getParameter("roomPwd");
			if (StringUtil.isNull(roomPwd)) {
				result.setMessage("房间密码为空！");
				return result;
			}

			pubgMatch.setRoomName(roomName);
			pubgMatch.setRoomPwd(roomPwd);

			// 比赛战队id和名称
			String matchTeamId = getParamValueString(request,"matchTeamId");
			if (StringUtil.isNull(matchTeamId)) {
				result.setMessage("比赛战队id为空！");
				return result;
			}
			String matchTeamName = getParamValueString(request,"matchTeamName");
			if (StringUtil.isNull(matchTeamName)) {
				result.setMessage("比赛战队名称为空！");
				return result;
			}

			pubgMatch.setMatchTeamId("," + matchTeamId);
			pubgMatch.setMatchTeamName(matchTeamName);
			pubgMatch.setCreateTime(DateUtil.getCurrentDateTime());

			String applyStartTime = getParamValueString(request,"applyStartTime");
			if (StringUtil.isEmpty(applyStartTime)) {
				result.setMessage("报名开始时间为空！");
				return result;
			}
			pubgMatch.setApplyStartTime(applyStartTime);

			String applyEndTime = getParamValueString(request,"applyEndTime");
			if (StringUtil.isEmpty(applyEndTime)) {
				result.setMessage("结束时间为空！");
				return result;
			}
			pubgMatch.setApplyEndTime(applyEndTime);

			String matchStartTime = getParamValueString(request,"applyStartTime");
			if (StringUtil.isEmpty(matchStartTime)) {
				result.setMessage("比赛开始时间为空！");
				return result;
			}
			pubgMatch.setMatchStartTime(matchStartTime);

			String matchEndTime = getParamValueString(request,"applyStartTime");
			if (StringUtil.isEmpty(matchEndTime)) {
				result.setMessage("比赛结束时间为空！");
				return result;
			}
			pubgMatch.setMatchEndTime(matchEndTime);

			String awardConfig = getStringValue(request,"awardConfig");
			if (StringUtil.isEmpty(awardConfig)) {
				result.setMessage("奖励设置为空！");
				return result;
			}

			String[] arr = awardConfig.split(",");
			for (String s : arr) {
			    if (Double.valueOf(s) < 0 || Double.valueOf(s) >= 1) {
                    result.setMessage("奖励设置值非法！");
                    return result;
                }
            }
			pubgMatch.setAwardConfig(awardConfig);
			
			String memberType = getStringValue(request,"memberType");
			if (StringUtil.isEmpty(memberType)) {
				result.setMessage("队员类型为空！");
				return result;
			}
			pubgMatch.setMemberType(memberType);

			boolean flag = this.pubgMatchService.saveMatch(pubgMatch, pubgUser);
			if (flag) {
				result.setData(pubgMatch);
				result.setCode(0);
				result.setMessage("添加赛事成功！");
			}
		} catch (Exception e) {
			log.error("添加赛事出错！", e);
		}
		return result;
	}

    /**
     * 赛事列表
     *
     */
    @ResponseBody
    @RequestMapping("/getMatchList")
	public Result<List<PubgMatch>> getMatchList(HttpServletRequest request, HttpServletResponse response, OPaging<PubgMatch> page, String token){
		Result<List<PubgMatch>> result = new Result<List<PubgMatch>>();
		result.setCode(-1);
		result.setMessage("获取赛事列表数据失败！");
        try{
        	Query query = new Query();
            String userId = tokenHandler.getCommUserInfoByToken(token);
            if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
            }
            PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));

            Long teamId = ObjectUtil.convert(getParamValueString(request, "teamId"), 0L);
            if (teamId == 0 && !UserConstant.USER_ROLE_30.getId().equals(pubgUser.getUserRole())) {
            	result.setMessage("请选择战队！");
            	return result;
			}
            
            if (teamId != 0 && UserConstant.USER_ROLE_30.getId().equals(pubgUser.getUserRole())) {
            	result.setMessage("请前往【我的】-【赛事管理】！");
            	return result;
			}
            
            // 如果是俱乐部 只查询 该俱乐部下的 赛事
            if (UserConstant.USER_ROLE_30.getId().equals(pubgUser.getUserRole())) {
            	query = new Query();
    			query.put("_LIKE$MINISTER_ID", "," + userId + ",");
    			PubgClub pubgClub = this.pubgClubService.find(query);
            	page.getWm().put("CLUB_ID", pubgClub.getRowId());
            }
            
            List<PubgUserTeam> pubgUserTeamList = new ArrayList<PubgUserTeam>();
            if (UserConstant.USER_ROLE_10.getId().equals(pubgUser.getUserRole())) {
            	query.put("USER_ID", userId);
            	query.put("TEAM_ID", teamId);
            	query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
            	pubgUserTeamList = this.pubgUserTeamService.findList(query);
            	if (pubgUserTeamList == null || pubgUserTeamList.isEmpty()) {
            		result.setMessage("请先加入战队！");
            		return result;
            	}
			} else if (UserConstant.USER_ROLE_20.getId().equals(pubgUser.getUserRole())) {
				PubgUserTeam pubgUserTeam = new PubgUserTeam();
				pubgUserTeam.setTeamId(teamId);
				pubgUserTeamList.add(pubgUserTeam);
			}
            
			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}

			// 排序方式
			String order = getParamValueString(request, "order");
			if (!StringUtil.isNotEmpty(order)) {
				order = " DESC ";
			}
			page.setOrder(order);

			// 排序字段
			String sort = getParamValueString(request, "sort");
			if (!StringUtil.isNotEmpty(sort)) {
				sort = " createTime";
			}
			page.setSort(sort);

            String matchTeamName = getParamValueString(request,"matchTeamName");
            if(!StringUtil.isNull(matchTeamName)){
				page.getWm().put("_LIKE$MATCH_TEAM_NAME", matchTeamName);
			}

            // 比赛状态
            String matchState = getParamValueString(request,"matchState");
            if (StringUtil.isNull(matchState)) {
            	result.setMessage("比赛状态参数缺少！");
        		return result;
            }else {
            	if(!"0".equals(matchState)){
					page.getWm().put("MATCH_STATE",matchState);
				}
			}
            // 创建时间
            String createTime = getParamValueString(request,"createTime");
            page.getWm().put("_LIKE&CREATE_TIME",createTime);

            String captionIds = "";
            for (PubgUserTeam pubgUserTeam : pubgUserTeamList) {
				captionIds += pubgUserTeam.getTeamId() + ",";
				page.getWm().put("MATCH_TEAM_ID&MATCH_TEAM_ID", "," + captionIds);
			}
            
            //返回的数据集合
            Map<String,String> columns = new HashMap<String,String>();
            columns.put("ROW_ID", "rowId");
            columns.put("CLUB_ID", "clubId");
            columns.put("CLUB_NAME", "clubName");
            columns.put("MATCH_NAME", "matchName");
            columns.put("MATCH_STATE", "matchState");
            columns.put("MATCH_MODE_ID", "matchModeId");
            columns.put("MATCH_MODE", "matchMode");
            columns.put("MATCH_TYPE_ID", "matchTypeId");
            columns.put("MATCH_TYPE", "matchType");
            columns.put("MATCH_START_TIME", "matchStartTime");
            columns.put("MATCH_END_TIME", "matchEndTime");
            columns.put("MATCH_TEAM_ID", "matchTeamId");
            columns.put("MEMBER_TYPE", "memberType");

			Paging<PubgMatch> pageTemp = this.pubgMatchService.findPage(columns , page);

			for (PubgMatch pubgMatch : pageTemp.getDataList()){
				String [] idArr = pubgMatch.getMatchTeamId().split(",");
				columns = new HashMap<String,String>();
				columns.put("TEAM_PHOTO", "teamPhoto");
				query = new Query();
				query.put("ROW_ID",idArr[1]);
				PubgTeam pubgTeam = this.pubgTeamService.find(columns, query);
				if (pubgTeam != null) {
					pubgMatch.setMatchPicUrl(pubgTeam.getTeamPhoto());
				}
			}

			result.setData(pageTemp.getDataList());
			result.setCode(0);
			result.setMessage("获取赛事列表成功！");
        }catch (Exception e){
            log.error("获取赛事列表失败",e);
        }
        return result;
    }


	/**
	 * 获取赛事详情
	 */
	@ResponseBody
	@RequestMapping("/matchDetail")
	public Result<PubgMatch> matchDetail(String token, HttpServletRequest request, HttpServletResponse response) {
		Result<PubgMatch> result = new Result<PubgMatch>();
		result.setCode(-1);
		result.setMessage("获取赛事详情失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			String id = getParamValueString(request,"id");
			if(StringUtil.isNull(id)){
				result.setMessage("赛事id缺少！");
				return result;
			}

			Map<String,String> columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			columns.put("CLUB_ID", "clubId");
			columns.put("CLUB_NAME", "clubName");
			columns.put("MATCH_NAME", "matchName");
			columns.put("MATCH_STATE", "matchState");
			columns.put("MATCH_MODE_ID", "matchModeId");
			columns.put("MATCH_MODE", "matchMode");
			columns.put("MATCH_TYPE_ID", "matchTypeId");
			columns.put("MATCH_TYPE", "matchType");
			columns.put("APPLY_START_TIME", "applyStartTime");
			columns.put("APPLY_END_TIME", "applyEndTime");
			columns.put("MATCH_START_TIME", "matchStartTime");
			columns.put("MATCH_END_TIME", "matchEndTime");
			columns.put("APPLY_FEE", "applyFee");
			columns.put("APPLY_PEOPLE_NUM", "applyPeopleNum");
			columns.put("MATCH_PEOPLE_NUM", "matchPeopleNum");
			columns.put("ROOM_NAME", "roomName");
            columns.put("ROOM_PWD", "roomPwd");
            columns.put("MATCH_TEAM_ID", "matchTeamId");
            columns.put("MATCH_TEAM_NAME", "matchTeamName");

			Query query = new Query();
			query.put("ROW_ID",id);
            PubgMatch pubgMatch = this.pubgMatchService.find(columns,query);
			if (StringUtil.isEmpty(pubgMatch)) {
				result.setMessage("赛事不存在！");
				return result;
			}

			// 当前登陆者为队员时，需要获取 队员-赛事的状态
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (UserConstant.USER_ROLE_10.getId().equals(pubgUser.getUserRole())) {
				Query queryUserMatch = new Query();
				queryUserMatch.put("MATCH_ID", pubgMatch.getRowId());
				queryUserMatch.put("CLUB_ID", pubgMatch.getClubId());
				queryUserMatch.put("USER_ID", userId);
				queryUserMatch.put("_IN$USER_STATE", UserMatchConstant.USER_MATCH_10.getId() + "," + UserMatchConstant.USER_MATCH_20.getId());
				queryUserMatch.orderBy("APPLY_TIME=DESC");
				List<PubgUserMatch> pubgUserMatchList = this.pubgUserMatchService.findList(queryUserMatch);
				
				if (pubgUserMatchList != null && pubgUserMatchList.size() > 0) {
					pubgMatch.setUserState(pubgUserMatchList.get(0).getUserState());
				}
			}

			//查询奖励说明
			columns = new HashMap<String,String>();
			columns.put("RANKING", "ranking");
			columns.put("AWARD_VALUE", "awardValue");
			query = new Query();
			query.put("MATCH_ID",id);
			List<PubgMatchReward> matchRewardList = this.pubgMatchRewardService.findList(columns,query);
			pubgMatch.setMatchRewardList(matchRewardList);
			result.setData(pubgMatch);
			result.setCode(0);
			result.setMessage("获取赛事详情成功！");
		} catch (Exception e) {
			log.error("获取赛事详情失败", e);
		}
		return result;
	}
}
